

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>1.20 合并多个字典或映射 &mdash; python3-cookbook 3.0.0 documentation</title>
  

  
  
  
  

  

  
  
    

  

  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
  <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="第二章：字符串和文本" href="../chapters/p02_strings_and_text.html" />
    <link rel="prev" title="1.19 转换并同时计算数据" href="p19_transform_and_reduce_data_same_time.html" /> 

  
  <script src="../_static/js/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav">

   
  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search">
          

          
            <a href="../index.html" class="icon icon-home"> python3-cookbook
          

          
          </a>

          
            
            
              <div class="version">
                3.0
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <ul class="current">
<li class="toctree-l1 current"><a class="reference internal" href="../chapters/p01_data_structures_algorithms.html">第一章：数据结构和算法</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="p01_unpack_sequence_into_separate_variables.html">1.1 解压序列赋值给多个变量</a></li>
<li class="toctree-l2"><a class="reference internal" href="p02_unpack_elements_from_iterables.html">1.2 解压可迭代对象赋值给多个变量</a></li>
<li class="toctree-l2"><a class="reference internal" href="p03_keep_last_n_items.html">1.3 保留最后 N 个元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p04_find_largest_or_smallest_n_items.html">1.4 查找最大或最小的 N 个元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p05_implement_a_priority_queue.html">1.5 实现一个优先级队列</a></li>
<li class="toctree-l2"><a class="reference internal" href="p06_map_keys_to_multiple_values_in_dict.html">1.6 字典中的键映射多个值</a></li>
<li class="toctree-l2"><a class="reference internal" href="p07_keep_dict_in_order.html">1.7 字典排序</a></li>
<li class="toctree-l2"><a class="reference internal" href="p08_calculating_with_dict.html">1.8 字典的运算</a></li>
<li class="toctree-l2"><a class="reference internal" href="p09_find_commonalities_in_dicts.html">1.9 查找两字典的相同点</a></li>
<li class="toctree-l2"><a class="reference internal" href="p10_remove_duplicates_from_seq_order.html">1.10 删除序列相同元素并保持顺序</a></li>
<li class="toctree-l2"><a class="reference internal" href="p11_naming_slice.html">1.11 命名切片</a></li>
<li class="toctree-l2"><a class="reference internal" href="p12_determine_most_freqently_items_in_seq.html">1.12 序列中出现次数最多的元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p13_sort_list_of_dicts_by_key.html">1.13 通过某个关键字排序一个字典列表</a></li>
<li class="toctree-l2"><a class="reference internal" href="p14_sort_objects_without_compare_support.html">1.14 排序不支持原生比较的对象</a></li>
<li class="toctree-l2"><a class="reference internal" href="p15_group_records_based_on_field.html">1.15 通过某个字段将记录分组</a></li>
<li class="toctree-l2"><a class="reference internal" href="p16_filter_sequence_elements.html">1.16 过滤序列元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p17_extract_subset_of_dict.html">1.17 从字典中提取子集</a></li>
<li class="toctree-l2"><a class="reference internal" href="p18_map_names_to_sequence_elements.html">1.18 映射名称到序列元素</a></li>
<li class="toctree-l2"><a class="reference internal" href="p19_transform_and_reduce_data_same_time.html">1.19 转换并同时计算数据</a></li>
<li class="toctree-l2 current"><a class="current reference internal" href="#">1.20 合并多个字典或映射</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#id2">问题</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id3">解决方案</a></li>
<li class="toctree-l3"><a class="reference internal" href="#id4">讨论</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../chapters/p02_strings_and_text.html">第二章：字符串和文本</a></li>
<li class="toctree-l1"><a class="reference internal" href="../aboutme.html">关于</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="../index.html">python3-cookbook</a>
        
      </nav>


      <div class="wy-nav-content">
        
        <div class="rst-content">
        
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="../index.html">Docs</a> &raquo;</li>
        
          <li><a href="../chapters/p01_data_structures_algorithms.html">第一章：数据结构和算法</a> &raquo;</li>
        
      <li>1.20 合并多个字典或映射</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="../_sources/c01/p20_combine_multiple_map_to_single_map.rst.txt" rel="nofollow"> View page source</a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="id1">
<h1>1.20 合并多个字典或映射<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h1>
<div class="section" id="id2">
<h2>问题<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>现在有多个字典或者映射，你想将它们从逻辑上合并为一个单一的映射后执行某些操作，
比如查找值或者检查某些键是否存在。</p>
</div>
<div class="section" id="id3">
<h2>解决方案<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h2>
<p>假如你有如下两个字典:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;x&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">3</span> <span class="p">}</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">4</span> <span class="p">}</span>
</pre></div>
</div>
<p>现在假设你必须在两个字典中执行查找操作（比如先从 <code class="docutils literal notranslate"><span class="pre">a</span></code> 中找，如果找不到再在 <code class="docutils literal notranslate"><span class="pre">b</span></code> 中找）。
一个非常简单的解决方案就是使用 <code class="docutils literal notranslate"><span class="pre">collections</span></code> 模块中的 <code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 类。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">ChainMap</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)</span>
<span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">])</span> <span class="c1"># Outputs 1 (from a)</span>
<span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;y&#39;</span><span class="p">])</span> <span class="c1"># Outputs 2 (from b)</span>
<span class="k">print</span><span class="p">(</span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;z&#39;</span><span class="p">])</span> <span class="c1"># Outputs 3 (from a)</span>
</pre></div>
</div>
</div>
<div class="section" id="id4">
<h2>讨论<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>一个 <code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 接受多个字典并将它们在逻辑上变为一个字典。
然后，这些字典并不是真的合并在一起了， <code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 类只是在内部创建了一个容纳这些字典的列表
并重新定义了一些常见的字典操作来遍历这个列表。大部分字典操作都是可以正常使用的，比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
<span class="go">[&#39;x&#39;, &#39;y&#39;, &#39;z&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>
<span class="go">[1, 2, 3]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>如果出现重复键，那么第一次出现的映射值会被返回。
因此，例子程序中的 <code class="docutils literal notranslate"><span class="pre">c['z']</span></code> 总是会返回字典 <code class="docutils literal notranslate"><span class="pre">a</span></code> 中对应的值，而不是 <code class="docutils literal notranslate"><span class="pre">b</span></code> 中对应的值。</p>
<p>对于字典的更新或删除操作总是影响的是列表中第一个字典。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;z&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;w&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">40</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">{&#39;w&#39;: 40, &#39;z&#39;: 10}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">&#39;y&#39;</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">KeyError</span>: <span class="n">&quot;Key not found in the first mapping: &#39;y&#39;&quot;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 对于编程语言中的作用范围变量（比如 <code class="docutils literal notranslate"><span class="pre">globals</span></code> , <code class="docutils literal notranslate"><span class="pre">locals</span></code> 等）是非常有用的。
事实上，有一些方法可以使它变得简单：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Add a new mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">values</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Add a new mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">values</span><span class="o">.</span><span class="n">new_child</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span>
<span class="go">ChainMap({&#39;x&#39;: 3}, {&#39;x&#39;: 2}, {&#39;x&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Discard last mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">values</span><span class="o">.</span><span class="n">parents</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Discard last mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">values</span><span class="o">.</span><span class="n">parents</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span>
<span class="go">ChainMap({&#39;x&#39;: 1})</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>作为 <code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 的替代，你可能会考虑使用 <code class="docutils literal notranslate"><span class="pre">update()</span></code> 方法将两个字典合并。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;x&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">3</span> <span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">4</span> <span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;y&#39;</span><span class="p">]</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;z&#39;</span><span class="p">]</span>
<span class="go">3</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>这样也能行得通，但是它需要你创建一个完全不同的字典对象（或者是破坏现有字典结构）。
同时，如果原字典做了更新，这种改变不会反应到新的合并字典中去。比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">1</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">ChainMap</span></code> 使用原来的字典，它自己不创建新的字典。所以它并不会产生上面所说的结果，比如：</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;x&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">3</span> <span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;z&#39;</span><span class="p">:</span> <span class="mi">4</span> <span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span> <span class="o">=</span> <span class="n">ChainMap</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">merged</span><span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">]</span> <span class="c1"># Notice change to merged dicts</span>
<span class="go">42</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
</div>


           </div>
           
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="../chapters/p02_strings_and_text.html" class="btn btn-neutral float-right" title="第二章：字符串和文本" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
        <a href="p19_transform_and_reduce_data_same_time.html" class="btn btn-neutral" title="1.19 转换并同时计算数据" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a>
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2017, 熊能.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'../',
            VERSION:'3.0.0',
            LANGUAGE:'None',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: '.txt'
        };
    </script>
      <script type="text/javascript" src="../_static/jquery.js"></script>
      <script type="text/javascript" src="../_static/underscore.js"></script>
      <script type="text/javascript" src="../_static/doctools.js"></script>

  

  <script type="text/javascript" src="../_static/js/theme.js"></script>

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script> 

</body>
</html>